#include "GeomCylinder.h"
#include "RotationConversion.h"

// Transform the ellpsoid by the inverse of Matrix
GeomObject* GeomCylinder::getObjApplyInvTransform(const Mat4d &_mat){ 
	printf("Error in line %d in file %s: Not Yet Implemented!\n", __LINE__, __FILE__);
	return new GeomCylinder(mRadius, mLength);
}

#define TESSELATION 16
extern unsigned int load_texture(char *filename);

void GeomCylinder::draw(Vec4d _color, bool _default){
	Vec4d col = _default? mColor : _color;
	glColor4dv( col.Ref() );

	static bool firstCall=true;
	if(mFirstDraw){
		mFirstDraw=false;
		//if(mTextureFileName) mTexture = load_texture(mTextureFileName);
	}

	if(mTextureFileName){
		glColor4d(1,1,1,1);	// white base for the texture
		glEnable(GL_TEXTURE_2D);
	}

	GLUquadric* cylinder = gluNewQuadric();
	GLUquadric* sphere = gluNewQuadric();
	glPushMatrix();
	getGLTransform();
	glMultMatrixd(mGLTransMat);
	glRotatef(mRotationXYZ[2],0,0,1);
	glRotatef(mRotationXYZ[1],0,1,0);
	glRotatef(mRotationXYZ[0],1,0,0);

	if(mTextureFileName){
		glBindTexture(GL_TEXTURE_2D, mTexture);
		glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
		gluQuadricTexture(sphere, true);
		gluQuadricTexture(cylinder, true);
	}
	//glutSolidSphere(mRadius,TESSELATION,TESSELATION);
	gluSphere(sphere, mRadius, TESSELATION,TESSELATION);
	glTranslatef(0,0,mLength);
	//glutSolidSphere(mRadius,TESSELATION,TESSELATION);
	gluSphere(sphere, mRadius, TESSELATION,TESSELATION);
	glTranslatef(0,0,-mLength);
	gluCylinder(cylinder,mLowerRadius, mRadius, mLength,TESSELATION,TESSELATION);
	glPopMatrix();
	gluDeleteQuadric(sphere);
	gluDeleteQuadric(cylinder);
	if(mTextureFileName){
		glDisable(GL_TEXTURE_2D);
	}
}

// default is oriented along z
Vec3d GeomCylinder::getOrientation(){
	return Rotation::EulerToMatrix(mRotationXYZ*M_PI/180, Rotation::XYZ) * Vec3d(0,0,1);
}
